/*
 *  $Id: StaticFieldsLocalizer.cs 1181 2010-11-10 16:08:03Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2010 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using System;
using System.Reflection;

using Nereal.Extensions;

namespace Ragima.Languages {
    /// <summary>
    /// Локализатор ресурсов, собирающий их из статических полей указанного типа.
    /// </summary>
    public class StaticFieldsLocalizer: DefaultLocalizer {
        public StaticFieldsLocalizer(Type fieldsType): this(fieldsType, GetResourceLang(fieldsType)) {}
        public StaticFieldsLocalizer(Type fieldsType, string langCode) : base(langCode) {
            foreach (var field in fieldsType.GetFields(BindingFlags.Public | BindingFlags.Static)) {
                if (typeof(ILocalized).IsAssignableFrom(field.FieldType)) {
                    var attr = field.GetAttribute<ResourceAttribute>();
                    var id = attr != null ? attr.Id : field.Name;
                    var resource = (ILocalized) field.GetValue(null);
                    AddResource(id, resource);
                }
            }
        }

        private static string GetResourceLang(Type type) {
            var attr = type.GetAttribute<ResourceLangAttribute>();
            return attr != null ? attr.LangCode : LanguageList.DefaultLanguageCode;
        }
    }
}
